<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input
            v-model="queryParams.templateName"
            placeholder="请输入模板名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="模板分类" prop="categoryId">
          <el-select v-model="queryParams.categoryId" placeholder="模板分类" clearable style="width: 200px">
            <el-option label="技术文档" value="1" />
            <el-option label="产品文档" value="2" />
            <el-option label="项目文档" value="3" />
            <el-option label="培训文档" value="4" />
            <el-option label="其他" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="模板状态" clearable style="width: 200px">
            <el-option label="启用" value="ENABLED" />
            <el-option label="禁用" value="DISABLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建者" prop="creatorName">
          <el-input
            v-model="queryParams.creatorName"
            placeholder="请输入创建者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 模板表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="templateList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="模板预览" align="center" width="100">
          <template #default="scope">
            <div class="template-preview" @click="handlePreview(scope.row)">
              <el-icon class="preview-icon"><Document /></el-icon>
              <span class="preview-text">预览</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="模板名称" align="center" prop="templateName" min-width="150" />
        <el-table-column label="模板分类" align="center" prop="categoryName" width="120" />
        <el-table-column label="模板描述" align="center" prop="description" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column label="使用次数" align="center" prop="usageCount" width="100">
          <template #default="scope">
            <span class="usage-count">{{ scope.row.usageCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="ENABLED"
              inactive-value="DISABLED"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否公开" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPublic ? 'success' : 'info'" size="small">
              {{ scope.row.isPublic ? '公开' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="creatorName" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handlePreview(scope.row)"
              link
            >预览</el-button>
            <el-button
              type="success"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              link
            >修改</el-button>
            <el-button
              type="info"
              icon="CopyDocument"
              @click="handleCopy(scope.row)"
              link
            >复制</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              link
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/编辑模板对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form :model="dialog.form" :rules="dialog.rules" ref="dialogFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="dialog.form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板分类" prop="categoryId">
              <el-select v-model="dialog.form.categoryId" placeholder="请选择模板分类" style="width: 100%">
                <el-option label="技术文档" value="1" />
                <el-option label="产品文档" value="2" />
                <el-option label="项目文档" value="3" />
                <el-option label="培训文档" value="4" />
                <el-option label="其他" value="5" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板状态" prop="status">
              <el-radio-group v-model="dialog.form.status">
                <el-radio label="ENABLED">启用</el-radio>
                <el-radio label="DISABLED">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否公开" prop="isPublic">
              <el-switch v-model="dialog.form.isPublic" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="dialog.form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <div class="editor-container">
            <el-input
              v-model="dialog.form.content"
              type="textarea"
              :rows="15"
              placeholder="请输入模板内容，支持Markdown格式"
            />
          </div>
        </el-form-item>
        <el-form-item label="模板标签" prop="tags">
          <el-tag
            v-for="tag in dialog.form.tags"
            :key="tag"
            closable
            @close="removeTag(tag)"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="dialog.tagInputVisible"
            ref="tagInputRef"
            v-model="dialog.tagInputValue"
            size="small"
            style="width: 100px"
            @keyup.enter="addTag"
            @blur="addTag"
          />
          <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="dialog.loading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog
      v-model="previewDialog.visible"
      title="模板预览"
      width="900px"
    >
      <div class="template-preview-content">
        <div class="preview-header">
          <h2>{{ previewDialog.template.templateName }}</h2>
          <div class="preview-meta">
            <span>分类：{{ previewDialog.template.categoryName }}</span>
            <span>创建者：{{ previewDialog.template.creatorName }}</span>
            <span>使用次数：{{ previewDialog.template.usageCount || 0 }}</span>
          </div>
        </div>
        <div class="preview-content" v-html="previewDialog.renderedContent"></div>
      </div>
      <template #footer>
        <el-button @click="previewDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="useTemplate">使用此模板</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getTemplatePage, 
  getTemplateDetail,
  createTemplate,
  updateTemplate,
  deleteTemplate,
  updateTemplateStatus,
  copyTemplate,
  exportTemplates
} from '@/api/document'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const templateList = ref([])
const queryFormRef = ref()
const dialogFormRef = ref()
const tagInputRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  templateName: undefined,
  categoryId: undefined,
  status: undefined,
  creatorName: undefined
})

// 对话框
const dialog = reactive({
  visible: false,
  title: '',
  loading: false,
  tagInputVisible: false,
  tagInputValue: '',
  form: {
    id: undefined,
    templateName: '',
    categoryId: undefined,
    description: '',
    content: '',
    status: 'ENABLED',
    isPublic: false,
    tags: []
  },
  rules: {
    templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
    categoryId: [{ required: true, message: '请选择模板分类', trigger: 'change' }],
    content: [{ required: true, message: '模板内容不能为空', trigger: 'blur' }]
  }
})

// 预览对话框
const previewDialog = reactive({
  visible: false,
  template: {},
  renderedContent: ''
})

// 获取模板列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getTemplatePage(queryParams)
    if (response.code === 200) {
      templateList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取模板列表失败')
    }
  } catch (error) {
    console.error('获取模板列表失败:', error)
    ElMessage.error('获取模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加模板'
  dialog.visible = true
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  const templateId = row.id || ids.value[0]
  try {
    const response = await getTemplateDetail(templateId)
    if (response.code === 200) {
      dialog.form = { ...response.data }
      dialog.title = '修改模板'
      dialog.visible = true
    }
  } catch (error) {
    console.error('获取模板详情失败:', error)
    ElMessage.error('获取模板详情失败')
  }
}

// 预览按钮操作
const handlePreview = async (row) => {
  try {
    const response = await getTemplateDetail(row.id)
    if (response.code === 200) {
      previewDialog.template = response.data
      // 这里可以添加Markdown渲染逻辑
      previewDialog.renderedContent = response.data.content.replace(/\n/g, '<br>')
      previewDialog.visible = true
    }
  } catch (error) {
    console.error('获取模板详情失败:', error)
    ElMessage.error('获取模板详情失败')
  }
}

// 复制按钮操作
const handleCopy = async (row) => {
  try {
    await copyTemplate(row.id)
    ElMessage.success('复制成功')
    getList()
  } catch (error) {
    console.error('复制模板失败:', error)
    ElMessage.error('复制模板失败')
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const templateIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除模板编号为"' + templateIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteTemplate(templateIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除模板失败:', error)
      ElMessage.error('删除模板失败')
    }
  }).catch(() => {})
}

// 状态修改
const handleStatusChange = async (row) => {
  const text = row.status === 'ENABLED' ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.templateName + '"模板吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updateTemplateStatus({ id: row.id, status: row.status })
    ElMessage.success(text + '成功')
  } catch (error) {
    row.status = row.status === 'ENABLED' ? 'DISABLED' : 'ENABLED'
  }
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportTemplates(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 提交表单
const submitForm = () => {
  dialogFormRef.value?.validate(async (valid) => {
    if (valid) {
      dialog.loading = true
      try {
        if (dialog.form.id) {
          await updateTemplate(dialog.form.id, dialog.form)
          ElMessage.success('修改成功')
        } else {
          await createTemplate(dialog.form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        dialog.loading = false
      }
    }
  })
}

// 使用模板
const useTemplate = () => {
  router.push({
    path: '/document/create',
    query: { templateId: previewDialog.template.id }
  })
}

// 标签操作
const showTagInput = () => {
  dialog.tagInputVisible = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

const addTag = () => {
  const tag = dialog.tagInputValue.trim()
  if (tag && !dialog.form.tags.includes(tag)) {
    dialog.form.tags.push(tag)
  }
  dialog.tagInputVisible = false
  dialog.tagInputValue = ''
}

const removeTag = (tag) => {
  const index = dialog.form.tags.indexOf(tag)
  if (index > -1) {
    dialog.form.tags.splice(index, 1)
  }
}

// 重置表单
const resetForm = () => {
  dialog.form = {
    id: undefined,
    templateName: '',
    categoryId: undefined,
    description: '',
    content: '',
    status: 'ENABLED',
    isPublic: false,
    tags: []
  }
}

// 工具函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.template-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .preview-icon {
    font-size: 24px;
    color: #409eff;
  }
  
  .preview-text {
    font-size: 12px;
    color: #606266;
  }
}

.usage-count {
  color: #e6a23c;
  font-weight: bold;
}

.editor-container {
  width: 100%;
  
  .el-textarea {
    font-family: 'Monaco', 'Consolas', monospace;
  }
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.template-preview-content {
  .preview-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
    
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
    }
    
    .preview-meta {
      display: flex;
      gap: 16px;
      font-size: 14px;
      color: #606266;
    }
  }
  
  .preview-content {
    max-height: 400px;
    overflow-y: auto;
    line-height: 1.6;
    color: #303133;
    
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin: 16px 0 8px 0;
      color: #303133;
    }
    
    :deep(p) {
      margin: 8px 0;
    }
    
    :deep(code) {
      background-color: #f5f5f5;
      padding: 2px 4px;
      border-radius: 3px;
      font-family: 'Monaco', 'Consolas', monospace;
    }
  }
}
</style>
